package com.cyj.qqserver.service;

import com.cyj.qqcommon.Message;
import com.cyj.qqcommon.MessageType;
import com.cyj.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * 服务端监听端口
 * 等待连接，保持通信
 */
public class QQServer {
    private ServerSocket ss=null;
    //也可用ConcurrentHashMap线程安全
    private static HashMap<String,User> validUsers=new HashMap<>();
    static {
        //初始化validUsers
        validUsers.put("100",new User("100","123456"));
        validUsers.put("200",new User("200","123456"));
        validUsers.put("袋袋",new User("300","123456"));
        validUsers.put("cyj",new User("1134623149","123456"));
    }
    //验证用户是否有效
    private boolean checkUser(String username,String password){
        User user=validUsers.get(username);
        if(user==null){//说明用户不存在数据库
            return false;
        }
        if (!(user.getUserpassword().equals(password))){
            return false;
        }
        return true;
    }

    public QQServer() {
        try {
            System.out.println("服务端在9999端口监听。。。。");
            ss=new ServerSocket(9999);
            while(true) {
                Socket socket=ss.accept();
                ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
                Object o = ois.readObject();
                User user=(User)o;
                //构建message对象回复客户端
                Message message=new Message();
                //验证
                if(checkUser(user.getUserid(),user.getUserpassword())){
                    message.setMessageType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    oos.writeObject(message);
                    //创建线程和客户端保持通信
                    ServerConnectClientThread serverConnectClientThread =
                            new ServerConnectClientThread(socket, user.getUserid());
                    serverConnectClientThread.start();
                    ManageServerConnectClientThread.addClient(user.getUserid(),serverConnectClientThread);
                } else {
                    //登陆失败
                    System.out.println("用户"+user.getUserid()+"   pwd="+user.getUserpassword()+"登录失败");
                    message.setMessageType(MessageType.MESSAGE_LOGIN_FAIL);
                    oos.writeObject(message);
                    socket.close();
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                ss.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
